/**
 * 验证类
 * @Author:linwt
 * @Time:2021/10/18
 * 
 */
import { rulesMap, IRulesMap } from "./rulesMap"

/**
 * 验证结果状态
 */
enum validStatus {
  SUCCESS = 1,
  FAIL = 0
}
/**
 * 统一验证结果返回接口
 */
interface IResultValid {
  [propName: string]: any
  errorList: Array<string>
  status: validStatus
}
/**
 * 验证接口
 */
interface IValidator {
  push: (ruleKey: string, value: string, msg: string) => void
  run: () => Promise<IResultValid[string]>
}

/**
 * 验证类
 */
class Validator implements IValidator {
  private caches!: Array<IRulesMap[string]>
  constructor () {
    this.caches = []
  }
  push (ruleKey: string, value: string, msg: string): void {
    const rulesFn = rulesMap[ruleKey]
    let fn = function () {
      return rulesFn(value, msg)
    }
    this.caches.push(fn)
  }
  run (): Promise<IResultValid[string]> {
    const resultValid: IResultValid = {
      errorList: [],
      status: validStatus.FAIL
    }
    for (const fn of this.caches) {
      const res = fn()
      if (res) {
        resultValid.errorList.push(res)
      }
    }
    if (resultValid.errorList.length) {
      resultValid.status = validStatus.FAIL
      return Promise.reject(resultValid.errorList)
    }
    return Promise.resolve(resultValid.status)
  }
}

export default Validator